package com.bizmda.bizsip.serveradaptor.protocol;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizMessage;
import com.bizmda.bizsip.common.BizResultEnum;
import com.bizmda.bizsip.config.AbstractServerAdaptorConfig;
import com.bizmda.bizsip.serveradaptor.protocol.java.JavaProtocolInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;

/**
 * @author 史正烨
 */
@Slf4j
public class RabbitmqServerProtocolProcessor extends AbstractServerProtocolProcessor {
    public static final String MQ_SERVER_EXCHANGE = "exchange.dircect.bizsip.mqserver";
    private RabbitTemplate rabbitTemplate = null;
    private String routeKey;

    @Override
    public void init(AbstractServerAdaptorConfig serverAdaptorConfig) throws BizException {
        super.init(serverAdaptorConfig);
        this.routeKey = (String)serverAdaptorConfig.getProtocolMap().get("route-key");
        if (rabbitTemplate == null) {
            rabbitTemplate = SpringUtil.getBean("rabbitTemplate");
        }
    }

    @Override
    public byte[] process(byte[] inMessage) throws BizException {
        String simpleUUID = IdUtil.simpleUUID();
        CorrelationData correlationData = new CorrelationData(simpleUUID);
        Object outMessage = rabbitTemplate.convertSendAndReceive(MQ_SERVER_EXCHANGE, this.routeKey, inMessage, correlationData);
        if (outMessage == null) {
            throw new BizException(BizResultEnum.MQ_SERVER_TIMEOUT);
        }
        log.info("outMessage:{}",outMessage);
        return (byte[])outMessage;
    }
}
